package com.dragon.mylibrary.db;

import android.database.Cursor;
import android.util.Log;


import com.dragon.mylibrary.info.UserInfo;
import com.dragon.utilslibrary.dblib.BaseDataDao;
import com.dragon.utilslibrary.dblib.dbutil.UsersUtil;

import java.util.List;

public class UserDao extends BaseDataDao<UserInfo> {

    private static final String TAG = "UserDao";

    @Override
    public String createTable() {
        return "create table if not exists tb_user(" +
                "userName Text," +
                "gender Integer," +
                "status Integer," +
                "weight Integer," +
                "height Integer," +
                "birth Text," +
                "number Text," +
                "calculating Text," +
                "sign Text," +
                "icon Text," +
                "goalStep Integer," +
                "goalWeight Integer," +
                "userId Text primary key);";
    }

    @Override
    public List<UserInfo> query(String sql) {
        String querySql = "select * from tb_user where " + sql + "";
        Log.i(TAG, "query: querySql--->" + querySql);
        Cursor cursor = getCursor(querySql);
        List<UserInfo> resultList = getResult(cursor, new UserInfo());
        return resultList;
    }

    @Override
    public boolean insertOrReplace(UserInfo entity) {
        if (entity == null || entity.getUserId() == null) {
            return false;
        }
        List<UserInfo> list = query(new UserInfo());
        for (UserInfo userInfo : list) {
            userInfo.setStatus(0);
            super.insertOrReplace(userInfo);
            UsersUtil.getInstance().initOnLogin(userInfo.getUserId());
        }
        entity.setStatus(1);
        boolean flag = super.insertOrReplace(entity);
        UsersUtil.getInstance().initOnLogin(entity.getUserId());
        return flag;
    }

    public void insertInfoList(List<UserInfo> list) {
        super.insertOrReplace(list);
    }

    public boolean insertInfo(UserInfo info) {
        return insertOrReplace(info);
    }

    public List<UserInfo> getAll() {
        List<UserInfo> list = query(new UserInfo());
        if (list != null && list.size() > 0) {
            return list;
        }
        return null;
    }

    public UserInfo getUserByUserId(String UserId) {
        UserInfo userInfo = null;
        String sql = "userId " + "='" + UserId + "'";
        List<UserInfo> list = query(sql);
        if (list != null && list.size() > 0) {
            userInfo = list.get(0);
        }
        return userInfo;
    }

    public int deleteAll() {
        int delete = delete(new UserInfo());
        return delete;
    }

    /**
     * get Current User Info
     *
     * @return
     */
    public UserInfo getCurrentUserInfo() {
        String sql = "status " + "='" + 1 + "'";
        List<UserInfo> list = query(sql);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

}
